package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.Result;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {


    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;


    /**
     * 负责查询对应时间段内的营业额数据
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {

        //目标dateList 日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03
        List<LocalDate> dateList = new ArrayList<>();//用于存放从begin到end范围内的每天的日期
        dateList.add(begin);
        while( !begin.equals(end) ){  //最后一次begin等于end 则停止了 而end已经在上一次放进去了
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        String dateLists = StringUtils.join(dateList, ",");//字符串工具，给每个list用逗号分割并且得到最终的string

        //目标turnoverList 营业额，以逗号分隔，例如：406.0,1520.0,75.0
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            //查询localDate日期对应的数据 营业额为状态为已完成的订单金额总计
            //需要把LocalDate格式完善为LocalDateTime 补全时分秒的信息
            LocalDateTime BeginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime EndTime = LocalDateTime.of(localDate,LocalTime.MAX);

            //select sum(amount) from orders where order_time > ? and order_time < ? and status = ?
            Map map = new HashMap();
            map.put("begin",BeginTime);
            map.put("end",EndTime);
            map.put("status", Orders.COMPLETED);
            Double turnOver = orderMapper.sumByMap(map);

            //如果当天营业额没有 那么最终拼接进去的就是null 这不合理 所以需要单独处理
            turnOver = turnOver == null ? 0.0 : turnOver;

            turnoverList.add(turnOver);
        }
        String turnOverLists = StringUtils.join(turnoverList, ",");

        return TurnoverReportVO
                .builder()
                .dateList(dateLists)
                .turnoverList(turnOverLists)
                .build();
    }


    /**
     * 根据起始时间进行用户数量相关的统计
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while( !begin.equals(end) ){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        String dateLists = StringUtils.join(dateList, ",");

        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();

        for (LocalDate localDate : dateList) {

            //时间的单独处理
            LocalDateTime BeginTime = LocalDateTime.of(localDate,LocalTime.MIN);
            LocalDateTime EndTime = LocalDateTime.of(localDate,LocalTime.MAX);

            //对于用户总量 select count(id) from user where create_time < ?
            Integer userNumber = userMapper.countUserNumberByTime(EndTime);
            userNumber = userNumber == null ? 0 : userNumber;

            //对于新增 select count(id) from user where create_time > ? and create_time < ?
            Integer userNew = userMapper.countUserNewByTime(BeginTime, EndTime);
            userNew = userNew == null ? 0 : userNew;

            newUserList.add(userNew);
            totalUserList.add(userNumber);

        }

        return UserReportVO
                .builder()
                .dateList(dateLists)
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();

    }

    /**
     * 订单统计接口
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while( !begin.equals(end) ){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> orderCountList = new ArrayList<>(); //每日订单数，以逗号分隔，例如：260,210,215
        List<Integer> validOrderCountList = new ArrayList<>();  //每日有效订单数，以逗号分隔，例如：20,21,10

        for (LocalDate localDate : dateList) {

            LocalDateTime beginTime = LocalDateTime.of(localDate,LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate,LocalTime.MAX);

            Integer orderNumber = orderMapper.getOrderNumberByTimeLT(beginTime,endTime);
            Integer UsefulOrderNumber = orderMapper.getUsefulOrderNumberByTimeLT(beginTime,endTime,Orders.COMPLETED);

            orderNumber = orderNumber == null ? 0 : orderNumber;
            UsefulOrderNumber = UsefulOrderNumber == null ? 0 : UsefulOrderNumber;

            orderCountList.add(orderNumber);
            validOrderCountList.add(UsefulOrderNumber);

        }

        LocalDateTime AllBeginTime = LocalDateTime.of(dateList.get(0),LocalTime.MIN);
        LocalDateTime AllEndTime = LocalDateTime.of(dateList.get(dateList.size() - 1),LocalTime.MAX);

        Integer totalOrderCount = orderMapper.getOrderNumberByTimeLT(AllBeginTime,AllEndTime);
        Integer validOrderCount = orderMapper.getUsefulOrderNumberByTimeLT(AllBeginTime,AllEndTime,Orders.COMPLETED);

        totalOrderCount = totalOrderCount == null ? 0 : totalOrderCount;
        validOrderCount = validOrderCount == null ? 0 : validOrderCount;

        Double orderCompletionRate;

        if(validOrderCount == 0 || totalOrderCount == 0){
            orderCompletionRate = 0.0;
        }else{
            orderCompletionRate = (double) validOrderCount / totalOrderCount;
        }

        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 展示销量前10的商品数据
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {

//        List<String> nameList = new ArrayList<>();
//        List<Integer> numberList = new ArrayList<>();

        //select od.name,sum(od.number) numbers from order_detail od, orders o where od.order_id = o.id
        // and o.status = 5 and o.order_time > ? and order_time < ? group by od.name
        // order by numbers desc limit 0,10
        //最核心的就是写好sql语句
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(
                LocalDateTime.of(begin, LocalTime.MIN),
                LocalDateTime.of(end, LocalTime.MAX),
                Orders.COMPLETED);
        //可以不通过for循环 通过stream流处理更快
        List<String> nameList = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();

    }

    /**
     * 导出Excel报表接口
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //查询数据库 获取需要的目标数据 查询最近30天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30); //30day ago
        LocalDate dateEnd = LocalDate.now().minusDays(1); //昨天

        BusinessDataVO businessData = workspaceService.getBusinessData(
                LocalDateTime.of(dateBegin,LocalTime.MIN),
                LocalDateTime.of(dateEnd,LocalTime.MAX)
        );


        //把查询到的数据通过spring-POI写入到excel文件中
        InputStream ln = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(ln); //基于模板文件 创建新的excel文件

            XSSFSheet sheet1 = excel.getSheet("Sheet1");
            //填充时间段的位置
            sheet1.getRow(1).getCell(1).setCellValue("时间:" + dateBegin + "至" + dateEnd);
            sheet1.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            sheet1.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            sheet1.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            sheet1.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            sheet1.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());



            //填充明细数据 30days
            for(int i = 0 ; i <30 ; i++){
                LocalDate date  = dateBegin.plusDays(i);
                BusinessDataVO dataVO = workspaceService.getBusinessData(
                        LocalDateTime.of(date, LocalTime.MIN),
                        LocalDateTime.of(date, LocalTime.MAX));
                XSSFRow row = sheet1.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(dataVO.getTurnover());
                row.getCell(3).setCellValue(dataVO.getValidOrderCount());
                row.getCell(4).setCellValue(dataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(dataVO.getUnitPrice());
                row.getCell(6).setCellValue(dataVO.getNewUsers());

            }

            //通过输出流把excel文件下载到客户端浏览器即可
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            //关闭资源
            outputStream.close();
            excel.close();

        } catch (IOException e) {
            e.printStackTrace();
        }




    }
}
